
import logging
from logging.handlers import SMTPHandler,RotatingFileHandler
import os
from config import Config
from flask import Flask
from app.auth import  auth_bp
from app.errors import  errors_bp
from app.main import  main_bp
from app.ext import bootstrap, db, login,mail, moment,migrate


def register_blueprints(app):
    app.register_blueprint(main_bp)
    app.register_blueprint(errors_bp)
    app.register_blueprint(auth_bp, url_prefix='/auth')


def register_extensions(app):
    bootstrap.init_app(app)
    db.init_app(app)
    login.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    migrate.init_app(app, db)
    

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    register_extensions(app)
    register_blueprints(app)

    if not app.debug and not app.testing:
        if app.config['MAIL_SERVER']:
            auth = None
            if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
                auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
            secure = None
            if app.config['MAIL_USE_TLS']:
                secure = ()
            mail_handler = SMTPHandler(
                                    mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                                    fromaddr='no-reply@' + app.config['MAIL_SERVER'],
                                    toaddrs=app.config['ADMINS'], subject='Starryblog Failure',
                                    credentials=auth, secure=secure)
            mail_handler.setLevel(logging.ERROR)
            app.logger.addHandler(mail_handler)
            if not os.path.exists('logs'):
                os.mkdir('logs')
            file_handler = RotatingFileHandler('logs/starryblog.log', maxBytes=10240,backupCount=10)
            file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
            file_handler.setLevel(logging.INFO)
            app.logger.addHandler(file_handler)
            
            app.logger.setLevel(logging.INFO)
            app.logger.info('Starryblog startup')
    return app



